import React, { useState, useEffect, useMemo, memo, useCallback } from 'react';
import moment from 'moment'
import { Empty } from 'antd'
import { useDispatch, useSelector } from 'dva'
import styles from './index.css'
import FundChart from './FundChart'
import Compute, { IComputeChangeValue } from './Compute'
import { RangePickerValue } from 'antd/lib/date-picker/interface';

interface DataItems {
  netValueDate: string;
  netValue: string;
  totalNetValue: string;
  dayOfGrowth: string;
}

interface IPageMainProps {
  fundDatas: DataItems[];
  funds: [string, string, string][];
  dispatch: any;
}

interface IPageMainState {
  rangeValue: RangePickerValue,
  fundCode: string
}

/**
 * 首页
 */
const PageMain = (props: IPageMainProps) => {
  const { fundDatas, funds } = useSelector(({ fundModel }) => {
    return {
      fundDatas: fundModel.fundDatas,
      funds: fundModel.funds
    }
  })

  const [rangeValue, setRangeValue] = useState<RangePickerValue>([moment().subtract(3, 'years'), moment()])
  const [fundCode, setFundCode] = useState<string>('100038')
  const dispatch = useDispatch()

  useEffect(() => {
    getFunds()
  }, [])

  useEffect(() => {
    getList()
  }, [rangeValue, fundCode])

  // 获取所有基金的信息（包括名字和基金代码）
  const getFunds = useCallback(() => {
    dispatch({
      type: 'fundModel/getFunds'
    })
  }, [])

  // 获取基金数据
  const getList = () => {
    const startDate = rangeValue[0].format('YYYY-MM-DD')
    const endDate = rangeValue[1].format('YYYY-MM-DD')
    const pageSize = rangeValue[1].diff(rangeValue[0], 'days')

    dispatch({
      type: 'fundModel/getDatas',
      payload: { fundCode, startDate, endDate, pageSize }
    })
  }

  // 渲染图表
  const handleChange = (params: IComputeChangeValue) => {
    if (params.fundCode) {
      setFundCode(params.fundCode)
    }
    if (params.rangeValue) {
      setRangeValue(params.rangeValue)
    }
  }


  // 渲染图表
  const renderChart = () => {
    if (fundDatas.length === 0) {
      return <Empty className={styles['empty-container']} />
    }
    return (<FundChart dataSource={fundDatas} />)
  }

  return (
    <div className={styles['container']}>
      {renderChart()}
      <Compute dataSource={fundDatas} onChange={handleChange} rangeValue={rangeValue} funds={funds} fundCode={fundCode} />
    </div>
  );
}

export default PageMain
